package com.cts.tmall.app.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cts.tmall.biz.service.PrdService;
import com.cts.tmall.biz.service.PropService;
import com.cts.tmall.biz.service.SkuService;
import com.cts.tmall.biz.service.SpecService;
import com.cts.tmall.dal.entity.*;
import com.cts.tmall.dal.mapper.TmallEvaMapper;
import com.cts.tmall.dal.mapper.TmallOrdMapper;
import org.apache.commons.lang3.RandomUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RestController
@RequestMapping("/api/prd")
public class PrdController extends BaseController<TmallPrd> {
    @Autowired
    private TmallOrdMapper ordMapper;

    @Autowired
    private TmallEvaMapper evaMapper;

    @Autowired
    private PropService propService;

    @Autowired
    private SpecService specService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private PrdService prdService;

    @PutMapping("/upd")
    public TmallPrd updateById(@RequestBody @Validated(Update.class) TmallPrd entity) {
        List skuList = entity.getSkuList();
        if (skuList != null && skuList.size() > 0) {
            Map skuItem = (Map) skuList.get(0);
            entity.setPrdPrice(Double.parseDouble(skuItem.get("price") == null ? "0" : skuItem.get("price").toString()));

            Long prdCount = 0L;
            for (int i = 0; i < skuList.size(); i++) {
                skuItem = (Map) skuList.get(i);
                prdCount += Long.parseLong(skuItem.get("stock") == null ? "0" : skuItem.get("stock").toString());
            }
            entity.setPrdCount(prdCount);
        }

        prdService.updateById(entity);

        if (entity.getPropList() != null && entity.getPropList().size() > 0) {
            propService.list(Wrappers.<Prop>lambdaQuery().eq(Prop::getGoodsNo, entity.getPrdNo())).stream().map(Prop::getPropNo).forEach(propNo -> {
                specService.remove(Wrappers.<Spec>lambdaQuery().eq(Spec::getPropNo, propNo));
                propService.remove(Wrappers.<Prop>lambdaQuery().eq(Prop::getPropNo, propNo));
            });
            List propList = entity.getPropList();
            propList.forEach(item -> {
                Map propItem = (Map) item;
                String propName = (String) propItem.get("propName");
                String propNo = String.valueOf(IdUtil.createSnowflake(1L, 1L).nextId());
                Prop prop = new Prop();
                prop.setPropNo(propNo);
                prop.setGoodsNo(entity.getPrdNo().toString());
                prop.setPropName(propName);
                propService.save(prop);


                List specList = (List) propItem.get("specList");
                specList.forEach(specItem -> {
                    Spec spec = new Spec();
                    spec.setSpecNo(String.valueOf(IdUtil.createSnowflake(1L, 1L).nextId()));
                    spec.setSpecName((String) specItem);
                    spec.setPropNo(propNo);
                    spec.setGoodsNo(entity.getPrdNo().toString());
                    spec.setChecked(1);
                    specService.save(spec);
                });
            });
        }

        if (entity.getSkuList() != null && entity.getSkuList().size() > 0) {
            skuService.remove(Wrappers.<Sku>lambdaQuery().eq(Sku::getGoodsNo, entity.getPrdNo()));

            skuList.forEach(skuItem -> {
                Map map = (Map) skuItem;
                Sku sku = new Sku();
                sku.setGoodsNo(entity.getPrdNo().toString());
                sku.setPropOne(map.get("specOneName") == null ? "" : map.get("specOneName").toString());
                sku.setPropTwo(map.get("specTwoName") == null ? "" : map.get("specTwoName").toString());
                sku.setStock(Integer.parseInt(map.get("stock") == null ? "0" : map.get("stock").toString()));
                sku.setPrice(Double.parseDouble(map.get("price") == null ? "0" : map.get("price").toString()));
                sku.setSku(map.get("sku") == null ? "" : map.get("sku").toString());
                skuService.save(sku);
            });
        }
        return entity;
    }


    @PostMapping("/save")
    public TmallPrd save(@RequestBody TmallPrd entity) {
        List skuList = entity.getSkuList();

        if (skuList.size() > 0) {
            Map skuItem = (Map) skuList.get(0);
            entity.setPrdPrice(Double.parseDouble(skuItem.get("price") == null ? "0" : skuItem.get("price").toString()));

            Long prdCount = 0L;
            for (int i = 0; i < skuList.size(); i++) {
                skuItem = (Map) skuList.get(i);
                prdCount += Long.parseLong(skuItem.get("stock") == null ? "0" : skuItem.get("stock").toString());
            }
            entity.setPrdCount(prdCount);
        }

        TmallPrd prd = super.save(entity);
        IntStream.range(0, 3).forEach(i -> {
            TmallOrd ord = new TmallOrd();
            ord.setOrdStatus("01");
            ord.setAfterSaleStatus("01");
            ord.setBizType("01");
            ord.setPayType("01");
            ord.setPrdNo(prd.getPrdNo());
            ord.setExpressOrg("01");
            ord.setExpressOrderNo("e0000000001");
            ord.setCustomName("顾客" + i);
            ord.setCustomTel("1888888888" + i);
            ord.setIsPresell("01");
            ord.setPrdType("01");
            ord.setAppChannel("01");
            ord.setCreateTime(new Date());
            ord.setFinishTime(new Date());
            ord.setCount(1);
            ord.setRealPrice(prd.getPrdPrice());
            ord.setCreateUserId(entity.getCreateUserId());
            ord.setSendStatus((RandomUtils.nextInt() / 2 == 0) ? "01" : "02");
            ordMapper.insert(ord);

            TmallEva eva = new TmallEva();
            eva.setPrdNo(prd.getPrdNo());
            eva.setPrdName(prd.getPrdName());
            eva.setEvaLevel(i % 2 == 0 ? "01" : "02");
            eva.setCustomNo("C15090712" + i);
            eva.setCreateTime(new Date());
            eva.setIsReturn("01");
            eva.setOrdNo(ord.getOrdNo());
            eva.setIsHaveImg("01");
            eva.setIsAddEva("01");
            eva.setIsChangeEva("01");
            eva.setPrdCrtUserNo(prd.getCreateUserId() == null ? "1" : prd.getCreateUserId().toString());
            eva.setCreateUserId(entity.getCreateUserId());
            evaMapper.insert(eva);
        });

        List propList = entity.getPropList();
        propList.forEach(item -> {
            Map propItem = (Map) item;
            String propName = (String) propItem.get("propName");
            String propNo = String.valueOf(IdUtil.createSnowflake(1L, 1L).nextId());
            Prop prop = new Prop();
            prop.setPropNo(propNo);
            prop.setGoodsNo(prd.getPrdNo().toString());
            prop.setPropName(propName);
            propService.save(prop);


            List specList = (List) propItem.get("specList");
            specList.forEach(specItem -> {
                Spec spec = new Spec();
                spec.setSpecNo(String.valueOf(IdUtil.createSnowflake(1L, 1L).nextId()));
                spec.setSpecName((String) specItem);
                spec.setPropNo(propNo);
                spec.setGoodsNo(prd.getPrdNo().toString());
                spec.setChecked(1);
                specService.save(spec);
            });
        });

        skuList.forEach(skuItem -> {
            Map map = (Map) skuItem;
            Sku sku = new Sku();
            sku.setGoodsNo(prd.getPrdNo().toString());
            sku.setPropOne(map.get("specOneName") == null ? "" : map.get("specOneName").toString());
            sku.setPropTwo(map.get("specTwoName") == null ? "" : map.get("specTwoName").toString());
            sku.setStock(Integer.parseInt(map.get("stock") == null ? "0" : map.get("stock").toString()));
            sku.setPrice(Double.parseDouble(map.get("price") == null ? "0" : map.get("price").toString()));
            sku.setSku(map.get("sku") == null ? "" : map.get("sku").toString());
            skuService.save(sku);
        });

        return prd;
    }

    @GetMapping("/detail/{prdNo}")
    public TmallPrd detailPrd(@PathVariable("prdNo") String prdNo) {
        TmallPrd tmallPrd = prdService.queryById(prdNo);

        List<Prop> props = propService.list(Wrappers.<Prop>lambdaQuery().eq(Prop::getGoodsNo, prdNo));
        List propList = props.stream().map(prop -> {
            Map map = new HashMap();
            map.put("propName", prop.getPropName());
            map.put("specList", specService.list(Wrappers.<Spec>lambdaQuery().eq(Spec::getPropNo, prop.getPropNo()))
                    .stream().map(Spec::getSpecName).collect(Collectors.toList()));
            return map;
        }).collect(Collectors.toList());

        List skuList = skuService.list(Wrappers.<Sku>lambdaQuery().eq(Sku::getGoodsNo, prdNo)).stream()
                .map(sku -> {
                    Map map = new HashMap();
                    map.put("specOneName", sku.getPropOne());
                    map.put("specTwoName", sku.getPropTwo());
                    map.put("stock", sku.getStock());
                    map.put("price", sku.getPrice());
                    map.put("sku", sku.getSku());
                    return map;
                }).collect(Collectors.toList());
        tmallPrd.setPropList(propList);
        tmallPrd.setSkuList(skuList);
        return tmallPrd;
    }
//    public TmallPrd save(@RequestBody @Validated(Insert.class) TmallPrd entity) {
//        TmallPrd prd = super.save(entity);
//
//        IntStream.range(0, 3).forEach(i -> {
//            TmallOrd ord = new TmallOrd();
//            ord.setOrdStatus("01");
//            ord.setAfterSaleStatus("01");
//            ord.setBizType("01");
//            ord.setPayType("01");
//            ord.setPrdNo(prd.getPrdNo());
//            ord.setExpressOrg("01");
//            ord.setExpressOrderNo("e0000000001");
//            ord.setCustomName("顾客" + i);
//            ord.setCustomTel("1888888888" + i);
//            ord.setIsPresell("01");
//            ord.setPrdType("01");
//            ord.setAppChannel("01");
//            ord.setCreateTime(new Date());
//            ord.setFinishTime(new Date());
//            ord.setCount(1);
//            ord.setRealPrice(prd.getPrdPrice());
//            ordMapper.insert(ord);
//
//            TmallEva eva = new TmallEva();
//            eva.setPrdNo(prd.getPrdNo());
//            eva.setPrdName(prd.getPrdName());
//            eva.setEvaLevel(i % 2 == 0 ? "01" : "02");
//            eva.setCustomNo("C15090712" + i);
//            eva.setCreateTime(new Date());
//            eva.setIsReturn("01");
//            eva.setOrdNo(ord.getOrdNo());
//            eva.setIsHaveImg("01");
//            eva.setIsAddEva("01");
//            eva.setIsChangeEva("01");
//            eva.setPrdCrtUserNo(prd.getCreateUserId() == null ? "1" : prd.getCreateUserId().toString());
//            evaMapper.insert(eva);
//        });
//        return prd;
//    }
}
